package com.bocai.grainshop.seckill.scheduled;

import com.bocai.grainshop.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@EnableAsync //开启异步 定时任务
@EnableScheduling //开启定时任务
public class SeckillScheduled {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    private final String upload_lock = "seckill:upload:lock";

    /**
     * @Author: SunJinbo
     * @Description  定时任务 加锁保证分布式情况下的幂等
     * @Param []
     * @return void
     * @Data Created in 2022/4/28 18:01
     */
    //@Scheduled(cron = "0 0 1/1 * * ?")
    @Scheduled(cron = "*/10 * * * * ?")
    public void uploadSkuSeckillShopForThree(){
        log.info("秒杀商品定时任务扫描中----->");
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillForThreeDays();
        }finally {
            lock.unlock();
        }
    }
}
